package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserService {
    @Autowired
    private UserFreezeService userFreezeService;
    @Autowired
    private SmsTemplate template;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserApi userApi;
    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 发送短信验证码
     *
     * @param phone
     */
    public ResponseEntity sendMsg(String phone) {
        User user = userApi.findByMobile(phone);
        if (user != null) {
            userFreezeService.checkUserStatus("1", user.getId());
        }

        //1、随机生成6位数字
//        String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //4、获取当前时间戳
        Long currentTime = System.currentTimeMillis();
        //查看redis中是否存入过当前手机号的验证码
        String redisCode = redisTemplate.opsForValue().get(Constants.SMS_CODE + phone);
        if (redisCode != null) {
            Long beforeTime = Long.valueOf(redisCode.split("_")[1]);
            //切割缓存获取时间戳
            if ((currentTime - beforeTime) < 60 * 1000) {
                return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body("请60秒后再次点击发送验证码！");
            }
        }
        //2、调用template对象，发送手机短信
//              template.sendSms(phone,code);
        //3、将验证码存入到redis,限时5分钟有效
        redisTemplate.opsForValue().set(Constants.SMS_CODE + phone, code + "_" + currentTime, Duration.ofMinutes(5));
        return ResponseEntity.ok(null);
    }


    /**
     * 验证登录
     *
     * @param phone
     * @param code
     */
    public Map loginVerification(String phone, String code) {
        //1、从redis中获取下发的验证码
        String beforeCode = redisTemplate.opsForValue().get(Constants.SMS_CODE + phone);
        String codeTwo = beforeCode.split("_")[0];
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if (StringUtils.isEmpty(codeTwo) || !codeTwo.equals(code)) {
            //验证码无效
            throw new RuntimeException("验证码错误！");
        }
        //3、删除redis中的验证码
        redisTemplate.delete(Constants.SMS_CODE + phone);
        //4、通过手机号码查询用户
        User user = userApi.findByMobile(phone);
        boolean isNew = false;
        //5、如果用户不存在，创建用户保存到数据库中
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userID = userApi.save(user);
            user.setId(userID);
            isNew = true;
            //注册环信账号
            extracted(user);
            log.info("用户注册信息{}", user);
            mqMessageService.sendLogService(userID, "0102", "user", null);
        }
        //6、通过JWT生成token(存入id和手机号码)
        Map tokenMap = new HashMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", phone);
        String token = JwtUtils.getToken(tokenMap);
        mqMessageService.sendLogService(user.getId(), "0101", "user", null);
        //7、构造返回值
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);
        return retMap;
    }

    /**
     * 异步执行抽取方法注册成为环信账户
     *
     * @param user
     */
    @Async
    public void extracted(User user) {
        String hxUser = Constants.HX_USER_PREFIX + user.getId();
        Boolean createUser = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
        if (createUser) {
            user.setHxUser(hxUser);
            user.setHxPassword(Constants.INIT_PASSWORD);
            userApi.update(user);
            log.info("环信用户注册信息{}", user);
        }
    }

    /**
     * 获取环信账号密码
     *
     * @return
     */
    public Map findById() {
        User byID = userApi.getByID(UserHolder.getUserId());
        Map map = new HashMap();
        map.put("username", byID.getHxUser());
        map.put("password", byID.getHxPassword());
        return map;
    }
}
